var pomelo = require('pomelo');
var crc = require('crc');
/**
 * Init app for client.
 */
var app = pomelo.createApp();
app.set('name', 'xxserver');

// app configuration
app.configure('production|development', 'gate', function(){
    console.log("set gate");
    app.set('connectorConfig',
        {
            connector : pomelo.connectors.hybridconnector,
            heartbeat : 3,
            useDict : true,
            useProtobuf : true
        }
    );
});

app.configure('production|development', 'connector', function(){
    console.log("set connector");
    app.set('connectorConfig',
        {
            connector : pomelo.connectors.hybridconnector,
            heartbeat : 3,
            useDict : true,
            useProtobuf : true
        }
    );
    require('mongodb').MongoClient.connect(
        "mongodb://mongo:27017/xxmajiang",
        function(err, db) {
            if (err) throw err;
            console.log("数据库连接已创建!");
            app.set("mongodb", db.db("xxmajiang"));
        }
    );
});
app.configure('production|development', function(){
    console.log("set route");
    app.route('room', function(session, msg, app, cb) {
        var roomServers = app.getServersByType('room');
    
        if(!roomServers || roomServers.length === 0) {
            cb(new Error('can not find room servers.'));
            return;
        }
        console.log("route roomId", session.get('roomId'));
        var index = Math.abs(crc.crc32(session.get('roomId'))) % roomServers.length; 
        console.log("room route ", session.get('roomId'), index);   
        cb(null, roomServers[index].id);
    });
});

// start app
app.start();

process.on('uncaughtException', function (err) {
    console.error(' Caught exception: ' + err.stack);
});
